package com.ambercrm.business.location;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.ambercrm.R;
import com.ambercrm.base.BaseTitleActivity;
import com.ambercrm.business.main.MainActivity;
import com.ambercrm.dialog_utils.BottomDialogTools;
import com.ambercrm.tools.ApkTools;
import com.ambercrm.tools.EmptyUtils;
import com.ambercrm.tools.MapUtils;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CheckLocationActivity extends BaseTitleActivity {

    private AMap aMap;
    private MapView mapView;      // 地图View

    TextView mMapTitleText;
    TextView mDistanceAndDetailAddrText;
    LinearLayout mNavLayout;
    String mAddress;
    String mName;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_check_location;
    }

    LatLng mStartLatLng, mDeslatLng;
    @Override
    protected void initContentView(View v) {
        mTitleText.setText("查看地址");
        mapView = v.findViewById(R.id.mapView);
        mMapTitleText = v.findViewById(R.id.map_title);
        mDistanceAndDetailAddrText = v.findViewById(R.id.distance_and_detail_addr_text);
        mNavLayout = v.findViewById(R.id.nav_layout);

        aMap = mapView.getMap();
        mapView.onCreate(mSavedInstanceState);// 此方法必须重写

        Bundle b = getBundle();
        final double latitude = b.getDouble("latitude");
        final double longitude = b.getDouble("longitude");
        mName = b.getString("name");
        mAddress = b.getString("address");
        mDeslatLng = new LatLng(latitude, longitude);

        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDeslatLng, 10));
        mMapTitleText.setText(mName);
        mDistanceAndDetailAddrText.setText("");

        // 初始化定位
        AndPermission.with(mContext)
                .runtime()
                .permission(new String[] {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
                .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        initLocation();
                    }
                })
                .onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(intent);
                    }
                })
                .start();

        mNavLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectMapDialog(latitude, longitude, null, mName);
            }
        });
    }

    private void addMarkerToMap() {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(mDeslatLng);
        markerOption.title(mName).snippet(mAddress);
        markerOption.draggable(false);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.mipmap.location_icon)));
        aMap.addMarker(markerOption);
    }

    private void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置返回地址信息，默认为true
        mLocationOption.setNeedAddress(true);
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    double longtitude = aMapLocation.getLongitude();
                    double latitude = aMapLocation.getLatitude();
                    mlocationClient.stopLocation();
                    mStartLatLng = new LatLng(latitude, longtitude);
                    mDistanceAndDetailAddrText.setText("距离" + MapUtils.calculateLineDistance(mStartLatLng, mDeslatLng) + " | " + mAddress);
                    addMarkerToMap();
                }
                else {
                    toast("定位失败");
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    private void showSelectMapDialog(final double latitude, final double longitude, final String startAddrName, final String endAddrName) {
        ArrayList<HashMap<String, String>> mapList = new ArrayList<>();
        boolean baiduInstall = ApkTools.isMapInstall(mContext, 0);
        HashMap<String, String> map = null;
        if (baiduInstall) {
            map = new HashMap<>();
            map.put("title", "百度地图");
            map.put("type", "baidu");
            mapList.add(map);
        }

        boolean gaodeInstall = ApkTools.isMapInstall(mContext, 1);
        if (gaodeInstall) {
            map = new HashMap<>();
            map.put("title", "高德地图");
            map.put("type", "gaode");
            mapList.add(map);
        }

        boolean tengxunInstall = ApkTools.isMapInstall(mContext, 2);
        if (tengxunInstall) {
            map = new HashMap<>();
            map.put("title", "腾讯地图");
            map.put("type", "tengxun");
            mapList.add(map);
        }

        if (EmptyUtils.isEmpty(mapList)) {
            toast("请安装地图软件");
            return;
        }

        if (mapList.size() == 1) {
            String type = mapList.get(0).get("type");
            if ("baidu".equals(type)) {
                // 打开百度地图导航
                MapUtils.goToBaiduMap(this, endAddrName, latitude, longitude);
            }
            else if ("gaode".equals(type)) {
                MapUtils.goToGaodeMap(this, endAddrName, latitude, longitude);
            }
            else if ("tengxun".equals(type)) {
                MapUtils.goTencentMap(this,null, null, latitude+","+longitude, endAddrName, getResources().getString(R.string.app_name));
            }
            return;
        }

        // 如果有多个地图， 请用户选择来导航
        BottomDialogTools.showBottomDialogText(mContext, true, mapList, "选择地图", new BottomDialogTools.BottomDialogAdapter.OnPopupClickListener() {
            @Override
            public void onClick(int position, Dialog dialog) {
                if (position == 0) {
                    // 打开百度地图导航
                    MapUtils.goToBaiduMap(mContext, endAddrName, latitude, longitude);
                }
                else if (position == 1) {
                    MapUtils.goToGaodeMap(mContext, endAddrName, latitude, longitude);
                }
                else if (position == 2) {
                    MapUtils.goTencentMap(mContext,null, null, latitude+","+longitude, endAddrName, getResources().getString(R.string.app_name));
                }
            }
        });
    }
}